<?php
class Archivo extends Controller {
	
  private $allowedExtensions = array('pdf');
  private $baseTargetPath = UPLOADS_PATH;
  
	public function __construct()
  {
    parent::Controller();
  }

  public function index() {
  	$this->load->view('upload_view');
  }
  
  public function getName($id) {
    echo File::getFilenameByDocument_Id($id);
  }
  
  public function remove($filename) {
    $target_path = $this->baseTargetPath.$filename;
    if (!is_file($target_path)) {
      echo json_encode(array('success' => false, 'errors' => array('title' => 'Error', 'errormsg' => 'El archivo '.$filename.' no existe. Contacte al administrador y pregunte por este problema.')));
      //echo '{success: false, errors: {title: "Error",errormsg: "El archivo '.$filename.' no existe. Contacte al administrador y pregunte por este problema."}}';    
      return false;
    }

    if (unlink($target_path)) {
      echo json_encode(array('success' => true));
      //echo '{success: true}';
      return true;
    }
    else {
      echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al remover', 'errormsg' => 'El archivo '.$filename.' no pudo ser eliminado. Contacte al administrador y pregunte por este problema.')));
      //echo '{success: false, errors: {title: "Error al remover",errormsg: "El archivo '.$filename.' no pudo ser eliminado. Contacte al administrador y pregunte por este problema."}}';    
      return false;  
    }
  }
  
  public function upload() {
    if ($_FILES['fileupload']['error'] == UPLOAD_ERR_OK) {
      $filename = $_FILES['fileupload']['name'];
      if (!$this->isAllowedExtension($filename, $this->allowedExtensions)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error', 'errormsg' => 'El archivo "'.$filename.'" contiene una extensi&oacute;n no v&aacute;lida o no es un archivo PDF.')));
        return false;
      }
      
      if (!is_writable($this->baseTargetPath)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al copiar archivo', 'errormsg' => 'El directorio "'.$this->baseTargetPath.'" no tiene permiso de escritura.')));
        return false;  
      }
      
  		$target_path = $this->baseTargetPath . $filename;
      if (is_file($target_path)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al copiar archivo', 'errormsg' => 'El archivo "'.$filename.'" ya existe en el servidor. Por favor, renombre el archivo he intente subirlo nuevamente.')));
        return false;  
      }
      
  		if (move_uploaded_file($_FILES['fileupload']['tmp_name'], $target_path) ) {
  			$output = json_encode(array('success' => true, 'filename' => $_FILES['fileupload']['name']));
  		}
  		else {
  		  $output = json_encode(array('success' => false, 'errors' => array('title' => 'Error copiando archivo!', 'errormsg' => 'Se ha producido un error al copiar el archivo subido al servidor.')));
  		}
    }
    else {
       $errorMessage = $this->fileUploadErrorMessage($_FILES['fileupload']['error']);
       $output = json_encode(array('success' => false, 'errors' => array('title' => 'Error copiando archivo!', 'errormsg' => $errorMessage)));
    }
		echo $output; 
  }
  
  public function uploadJReport() {
//    $_REQUEST['report_id']
//    $_REQUEST['description']
    
    if ($_FILES['fileupload']['error'] == UPLOAD_ERR_OK) {
      if (!$this->isAllowedExtension($_FILES['fileupload']['name'], array('jrxml', 'jrpxml', 'xml'))) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error', 'errormsg' => 'El archivo seleccionado no tiene una extensi&oacute;n v&aacute;lida de archivo Jasper Report XML (*.jrxml | *.xml).')));
        return false;
      }
      
      $baseTargetPath = JASPER_REPORT_UPLOADS_PATH;
      if (!file_exists($baseTargetPath)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al copiar archivo', 'errormsg' => 'El directorio "'.$baseTargetPath.'" no existe.')));
        return false;  
      }
      
      if (!is_writable($baseTargetPath)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al copiar archivo', 'errormsg' => 'El directorio "'.$baseTargetPath.'" no tiene permiso de escritura.')));
        return false;  
      }
      
  		$target_path = $baseTargetPath . $_FILES['fileupload']['name'];
      if (is_file($target_path)) {
        echo json_encode(array('success' => false, 'errors' => array('title' => 'Error al copiar archivo', 'errormsg' => 'El archivo ya existe en el servidor. Por favor, renombre el archivo he intente subirlo nuevamente.')));
        return false;  
      }
      
      // here is where the success action occur 
  		if (move_uploaded_file($_FILES['fileupload']['tmp_name'], $target_path) ) {
  			$output = json_encode(array('success' => true, 'filename' => $_FILES['fileupload']['name']));
  		}
  		else {
  		  $output = json_encode(array('success' => false, 'errors' => array('title' => 'Error copiando archivo!', 'errormsg' => 'Se ha producido un error al copiar el archivo subido al servidor.')));
  		}
    }
    else {
       $errorMessage = $this->fileUploadErrorMessage($_FILES['fileupload']['error']);
       $output = json_encode(array('success' => false, 'errors' => array('title' => 'Error copiando archivo!', 'errormsg' => $errorMessage)));
    }
		echo $output; 
  }
  
  public function download($filename) {
    // open the file in a binary mode
    $filepath = $this->baseTargetPath.$filename;
    $fp = fopen($filepath, 'rb');
    
    // We'll be outputting a PDF
    header('Content-type: application/pdf');
    // It will be called downloaded.pdf
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header("Content-Length: " . filesize($filepath));
    
    // dump the picture and stop the script
    fpassthru($fp);
    exit;
  }
  
  public function open($filename) {
    // open the file in a binary mode
    $filepath = $this->baseTargetPath.$filename;
    $fp = fopen($filepath, 'rb');
    
    // We'll be outputting a PDF
    header('Content-type: application/pdf');
    // It will be called downloaded.pdf
    //header('Content-Disposition: attachment; filename="'.$filename.'"');
    header("Content-Length: " . filesize($filepath));
    
    // dump the picture and stop the script
    fpassthru($fp);
    exit;
  }
  
  public static function isAllowedExtension($fileName, array $allowedExtensions) {
    return in_array(end(explode(".", $fileName)), $allowedExtensions);
  }
  
  // TODO: cambiar los mensajes en ingles por mensages en español
  public static function fileUploadErrorMessage($errorCode) {
    switch ($errorCode) { 
      case UPLOAD_ERR_INI_SIZE: 
          $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
          break; 
      case UPLOAD_ERR_FORM_SIZE: 
          $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
          break; 
      case UPLOAD_ERR_PARTIAL: 
          $message = "The uploaded file was only partially uploaded"; 
          break; 
      case UPLOAD_ERR_NO_FILE: 
          $message = "No file was uploaded"; 
          break; 
      case UPLOAD_ERR_NO_TMP_DIR: 
          $message = "Missing a temporary folder"; 
          break; 
      case UPLOAD_ERR_CANT_WRITE: 
          $message = "Failed to write file to disk"; 
          break; 
      case UPLOAD_ERR_EXTENSION: 
          $message = "File upload stopped by extension"; 
          break; 
  
      default: 
          $message = "Unknown upload error"; 
          break; 
    } 
    return $message;  
  } 
  
}